import 'package:flutter/material.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/pages/basic/estate/model.dart';
import 'package:flutter_smart_heating/pages/information/map/map.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';

import '../../information/station/view/status.dart';
//import 'package:map_launcher/map_launcher.dart';

class BasicEstateDetailPage extends StatefulWidget {
  const BasicEstateDetailPage({super.key});

  @override
  State<BasicEstateDetailPage> createState() => _BasicEstateDetailPageState();
}

class _BasicEstateDetailPageState extends State<BasicEstateDetailPage> {
  BasicEstateModel estate = BasicEstateModel();
  Map<String, dynamic> status = {};

  fetchData() async {
    var res = await Http.instance
        .post('/api/basic/estate/detail', data: {'id': Get.parameters['id']});
    setState(() {
      estate = BasicEstateModel.fromJson(res.data);
    });
    if (res.code == 1) {
      fetchStatus();
    }
  }

  fetchStatus() async {
    var res = await Http.instance.post('/api/information/station/status',
        data: {'station_id': estate.stationId});
    if (res.code == 1) {
      setState(() {
        status = res.data;
      });
    }
  }

  bool get isBlock => estate.id == null;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(estate.name ?? '小区详情'),
        actions: const [
          UiRightMenuButtonGroup(),
        ],
      ),
      body: UiLifeCycle(
        onRouteDone: fetchData,
        child: ListView(
          padding: const EdgeInsets.only(
            top: UiTheme.toolbarSpacing,
            left: UiTheme.spacingX,
            right: UiTheme.spacingX,
          ),
          children: [
            UiPanel(
              children: [
                cell(
                  icon: UiIcons.company,
                  title: '所属企业',
                  trailing: Text(Ui.getString(estate.companyName, '--')),
                ),
                cell(
                  icon: UiIcons.station,
                  title: '所属热站',
                  trailing: Text(Ui.getString(estate.stationName, '--')),
                ),
                cell(
                  icon: UiIcons.border_outer,
                  title: '小区面积',
                  trailing: Text('${estate.area}平方米'),
                ),
                cell(
                  icon: UiIcons.team,
                  title: '居民人数',
                  trailing: Text('${estate.population}人'),
                ),
                cell(
                  icon: UiIcons.solution,
                  title: '联系姓名',
                  trailing: Text(Ui.getString(estate.linkman, '--')),
                ),
                cell(
                  icon: UiIcons.phone,
                  title: '联系电话',
                  trailing: Text(Ui.getString(estate.linkphone, '--')),
                  showDivider: false,
                  onTap: () {
                    Ui.makePhoneCall(estate.linkphone);
                  },
                ),
              ],
            ),
            const UiLineBreak(),
            UiPanel(
              children: [
                cell(
                  icon: UiIcons.location,
                  title: Ui.getString(estate.address, '暂无地址'),
                  showDivider: false,
                  showArrow: true,
                  onTap: () {
                    InformationMapPage.show(
                      context,
                      name: estate.name,
                      address: estate.address,
                      location: MapCoordinate(
                        double.tryParse(estate.latitude ?? '0') ?? 0,
                        double.tryParse(estate.longitude ?? '0') ?? 0,
                      ),
                    );
                  },
                ),
                if (estate.showMap == true)
                  SizedBox(
                    height: 250,
                    child: BMFMapWidget(
                      onBMFMapCreated: (controller) {
                        BMFText bmfText = BMFText(
                          text: '● ${estate.name} ',
                          paragraphSpacing: 10,
                          position: BMFCoordinate(
                            double.tryParse(estate.latitude ?? '0') ?? 0,
                            double.tryParse(estate.longitude ?? '0') ?? 0,
                          ),
                          bgColor: UiTheme.primary,
                          fontColor: Colors.white,
                          fontSize: 15,
                          alignment: BMFTextAlignment.center,
                          typeFace: BMFTypeFace(
                            textStype: BMFTextStyle.BOLD,
                          ),
                          zIndex: 100,
                          lineSpacing: 10,
                          rotate: 0,
                        );
                        controller.addText(bmfText);
                      },
                      mapOptions: BMFMapOptions(
                        overlookEnabled: false,
                        rotateEnabled: false,
                        center: BMFCoordinate(
                          double.tryParse(estate.latitude ?? '0') ?? 0,
                          double.tryParse(estate.longitude ?? '0') ?? 0,
                        ),
                        zoomLevel: 16,
                      ),
                    ),
                  ),
              ],
            ),
            SafeArea(
              top: false,
              bottom: true,
              minimum: const EdgeInsets.only(bottom: UiTheme.spacingX),
              child: Container(),
            ),
          ],
        ),
      ),
      bottomNavigationBar: isBlock
          ? null
          : SafeArea(
              bottom: true,
              minimum: const EdgeInsets.only(bottom: 20),
              child: UiTap(
                onTap: () {
                  StationStatusView.show(context,
                      id: estate.stationId, status: status);
                },
                child: UiPanel(
                  height: 50,
                  padding:
                      const EdgeInsets.symmetric(horizontal: UiTheme.spacingX),
                  margin:
                      const EdgeInsets.symmetric(horizontal: UiTheme.spacingX),
                  child: Row(
                    children: [
                      const Icon(Icons.device_hub, size: 16),
                      const SizedBox(width: 3),
                      const Text('运行状态：'),
                      Text(
                        status['status_name'] ?? '--',
                        style: status['status'] == null
                            ? null
                            : TextStyle(
                                color: status['status'] == 'online'
                                    ? const Color.fromARGB(255, 51, 179, 55)
                                    : Colors.redAccent,
                              ),
                      ),
                      Expanded(child: Container()),
                      const Icon(Icons.history, size: 16),
                      const SizedBox(width: 3),
                      const Text('最后更新：'),
                      Text(status['update_time_short'] ?? '--'),
                    ],
                  ),
                ),
              ),
            ),
    );
  }

  Widget cell({
    required IconData icon,
    required String title,
    Function()? onTap,
    bool showDivider = true,
    bool showArrow = false,
    Widget? trailing,
  }) {
    return UiListCell(
      onTap: onTap,
      leading: UiLinearGradientMask(
          child: UiIcon(
        icon,
        color: Colors.white,
      )),
      leadingSpace: 10,
      title: isBlock ? const UiBlock(height: 15, width: 300) : Text(title),
      showArrow: isBlock ? false : showArrow,
      showDivider: showDivider,
      dividerIndent: 50,
      trailing: isBlock ? null : trailing,
      backgroundColor: Colors.transparent,
    );
  }

  openMapsSheet(
    context, {
    double latitude = 0,
    double longitude = 0,
    String? title,
  }) async {
    // try {
    //   final availableMaps = await MapLauncher.installedMaps;
    //   showModalBottomSheet(
    //     context: context,
    //     builder: (BuildContext context) {
    //       return SafeArea(
    //         child: SingleChildScrollView(
    //           child: Wrap(
    //             children: <Widget>[
    //               for (var map in availableMaps)
    //                 ListTile(
    //                   onTap: () => map.showMarker(
    //                       coords: Coords(latitude, longitude),
    //                       title: title ?? '地图导航'),
    //                   title: Text(map.mapName.tr),
    //                   leading: const Icon(Icons.map, size: 30),
    //                 ),
    //             ],
    //           ),
    //         ),
    //       );
    //     },
    //   );
    // } catch (e) {
    //   print(e);
    // }
  }
}
